%:- 
use_module(library(lists)).

% task 2 (2p)
?- A=triple(E1,E2,B), E1=[A|B]-B, X=triple(E2,E1,A).

% task 3          (4p)

clause(H,B) --> head(H), "-->", body(B), ".".
:- listing(clause/4).

% task 4          (8p)

%activity(Name, FollowedBy).

activity('Putting the kettle on', ['Drinking tea']).
activity('Watching TV', ['Putting the kettle on','Watching TV','Going to sleep']).
activity('Drinking tea', ['Watching TV','Going to sleep']).
activity('Going to sleep',[]).

is_allowed_schedule([p(Time,Aname)]) :- % last activity
        activity(Aname,_), !.  
is_allowed_schedule([p(Time,Aname),p(NextTime,Next)|T]) :- 
        activity(Aname,FollowedBy),
        member(Next,FollowedBy), % all others before last must have followers
        !,
        NextTime is Time+1,        % check that NextTime is exactly one time unit later (consecutive)
        is_allowed_schedule([p(NextTime,Next)|T]).
is_allowed_schedule([]). % An empty schedule is also a schedule...

gensched([],_,_).
gensched([p(I,H)|T],H,I) :- 
        activity(H,N), 
        member(M,N),
        I1 is I+1,
        gensched(T,M,I1).

?- length(S,9), gensched(S,_,3), is_allowed_schedule(S), write(task5(S)), nl.

% task 5          (8p)

rect(r1, 0,0,5,5).
rect(r2, 1,1,7,4).
rect(r3, 4,3,5,7).
rect(r4, 5,3,9,7).
rect(r5, 5,2,7,6).
rect(r6, 3,6,5,8).
rect(r7, 2,1,5,6).

overlap(Rect1,Rect2) :- overlapping(Rect1,Rect2).
overlap(Rect1,Rect2) :- overlapping(Rect2,Rect1).

overlapping(Rect2,Rect1) :-
    rect(Rect1,Ulx1,Uly1,Lrx1,Lry1), 
    rect(Rect2,Ulx2,Uly2,Lrx2,Lry2),
    Rect1\=Rect2,
    Lrx1>Ulx2, Lry1>Uly2, Ulx1<Lrx2, Uly1<Lry2.

% I check that there is an area inside each rectangle that overlaps with all the other rectangles.

joined([]).
joined([R|Rs]) :- joined(Rs,R), joined(Rs).

joined([],_).
joined([R2|T],R1) :- overlapping(R1,R2), joined(T,R1).

% An alternative (unintended by me) interpretation is to divide the set of rectangles
% into groups of two or three (if the number is odd) and to check that each pair of
% rectangles share an area, i.e. the two (or three) rectangles
% overlap (without bothering about the rest). 

% task 6 (6p)

% a
l2r([H|T],R) :- l2r(T,H,S,1,N), R=[p(N,H)|U], l2r(S,U). % first occurence of H in a group
l2r([],[]).

l2r([H|T],H,S,I,N) :- !, I1 is I+1, l2r(T,H,S,I1,N).  % found the same character again
l2r(L,_,L,I,I). % found some other character or end of list


% b
r2l([],[]).
r2l([p(0,_)|S],T) :- !, r2l(S,T).
r2l([p(N,H)|S],[H|T]) :- N>0, N1 is N-1, r2l([p(N1,H)|S],T).


% task 7 a       (3 of 6p)

dapp(A-B,B-C,A-C).
dapp3(L1,L2,L3,L) :- dapp(L1,L2,Lt), dapp(Lt,L3,L).

:- listing.

